﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class cms_AddNewUserInfo : System.Web.UI.Page
{
    private int Id = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["user"] == null)
        {
            Response.Redirect("Default.aspx");
        }
        if (!IsPostBack)
        {
            DataRow dr = (DataRow)Session["user"];
            if (!Convert.ToBoolean(dr["IsAdmin"]))
            {
                Response.Redirect("ListUserInfo.aspx");
            }

            if (!string.IsNullOrEmpty(Request.QueryString["Id"]))
            {
                Id = Convert.ToInt32(Request.QueryString["Id"]);
                txtUsername.Enabled = false;
                RequiredPassword.Visible = false;
                btnAdd.Text = "Update";
                //set info
                DBClass db = new DBClass();
                DataSet ds = db.GetAllUserInfo(Id);
                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    dr = ds.Tables[0].Rows[0];
                    txtUsername.Text = Convert.ToString(dr["Username"]);
                    txtFirstName.Text = Convert.ToString(dr["FirstName"]);
                    txtLastName.Text = Convert.ToString(dr["LastName"]);
                    txtEmail.Text = Convert.ToString(dr["Email"]);
                    txtPhone.Text = Convert.ToString(dr["Phone"]);
                    chkEnable.Checked = Convert.ToBoolean(dr["IsEnabled"]);
                    chkAdmin.Checked = Convert.ToBoolean(dr["IsAdmin"]);
                }
            }
            else
            {
                trEnable.Visible = false;
                btnAdd.Text = "Add Now";
            }
        }
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        DBClass db = new DBClass();
        if (!string.IsNullOrEmpty(Request.QueryString["Id"]))
        {
            Id = Convert.ToInt32(Request.QueryString["Id"]);
            db.UpdateUserInfo(Id, txtUsername.Text.Trim(), txtPassword.Text.Trim(), txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim(), chkEnable.Checked, chkAdmin.Checked, txtPhone.Text.Trim());
        }
        else
        {
            int i = db.InsertUserInfo(txtUsername.Text.Trim(), txtPassword.Text.Trim(), txtFirstName.Text.Trim(), txtLastName.Text.Trim(), txtEmail.Text.Trim(), true, chkAdmin.Checked, txtPhone.Text.Trim());
            if (i == -1)
            {
                lbError.Text = "Username exits.";
                return;
            }
        }
        Response.Redirect("ListUserInfo.aspx");
    }
}